import { axiosInstance } from "@halo-dev/api-client";
import type {
  ProductType,
  Product,
  ProductTypeListResponse,
  ProductListResponse,
  ProductTypeListRequest,
  ProductListRequest,
  CreateProductTypeRequest,
  UpdateProductTypeRequest,
  DeleteProductTypeRequest,
  CreateProductRequest,
  UpdateProductRequest,
  DeleteProductRequest,
} from "@/types";

export const productTypeApiClient = {
  listProductTypes: (params: ProductTypeListRequest) => {
    const { page, size, keyword } = params;
    const searchParams = new URLSearchParams();
    
    if (page !== undefined) searchParams.set("page", page.toString());
    if (size !== undefined) searchParams.set("size", size.toString());
    if (keyword) searchParams.set("keyword", keyword);
    
    return axiosInstance.get<ProductTypeListResponse>(
      `/apis/content.halo.run/v1alpha1/product-types?${searchParams.toString()}`
    );
  },

  getProductType: (name: string) => {
    return axiosInstance.get<ProductType>(
      `/apis/content.halo.run/v1alpha1/product-types/${name}`
    );
  },

  createProductType: (data: CreateProductTypeRequest) => {
    return axiosInstance.post<ProductType>(
      `/apis/content.halo.run/v1alpha1/product-types`,
      data.productType
    );
  },

  updateProductType: (data: UpdateProductTypeRequest) => {
    return axiosInstance.put<ProductType>(
      `/apis/content.halo.run/v1alpha1/product-types/${data.name}`,
      data.productType
    );
  },

  deleteProductType: (data: DeleteProductTypeRequest) => {
    return axiosInstance.delete(
      `/apis/content.halo.run/v1alpha1/product-types/${data.name}`
    );
  },
};

export const productApiClient = {
  listProducts: (params: ProductListRequest) => {
    const { page, size, keyword, productTypeRef } = params;
    const searchParams = new URLSearchParams();
    
    if (page !== undefined) searchParams.set("page", page.toString());
    if (size !== undefined) searchParams.set("size", size.toString());
    if (keyword) searchParams.set("keyword", keyword);
    if (productTypeRef) searchParams.set("productTypeRef", productTypeRef);
    
    return axiosInstance.get<ProductListResponse>(
      `/apis/content.halo.run/v1alpha1/products?${searchParams.toString()}`
    );
  },

  getProduct: (name: string) => {
    return axiosInstance.get<Product>(
      `/apis/content.halo.run/v1alpha1/products/${name}`
    );
  },

  createProduct: (data: CreateProductRequest) => {
    return axiosInstance.post<Product>(
      `/apis/content.halo.run/v1alpha1/products`,
      data.product
    );
  },

  updateProduct: (data: UpdateProductRequest) => {
    return axiosInstance.put<Product>(
      `/apis/content.halo.run/v1alpha1/products/${data.name}`,
      data.product
    );
  },

  deleteProduct: (data: DeleteProductRequest) => {
    return axiosInstance.delete(
      `/apis/content.halo.run/v1alpha1/products/${data.name}`
    );
  },
};